<template>
  <div v-cloak class="app-container" style="padding:0px;">
    <div style="width: 100%;height:400px;overflow-y: scroll;display: flex;align-items: flex-start;">
      <div class="r">
        <el-card shadow="never" class="cardBg" style="padding-top:0px">
          <el-table v-loading="listLoading" :data="skuList" style="width: 100%;margin-top: 0px" border>
            <el-table-column label="SKU编码" width="150" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.skuCode" oninput="value=value.replace(/[^\d]/g,'')" disabled />
              </template>
            </el-table-column>
            <!-- 销售属性列动态显示 -->
            <el-table-column v-for="(item,index) in templateNameList" :key="item.id" :label="templateNameList[index]" width="100" align="center">
              <template slot-scope="scope">
                {{ getProductSkuSp(scope.row,index) }}
              </template>
            </el-table-column>
            <el-table-column label="原价" width="100" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.skuCostprice" onkeyup="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''" disabled />
              </template>
            </el-table-column>
            <el-table-column label="现价" width="100" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.skuSaleprice" onkeyup="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''" disabled />
              </template>
            </el-table-column>
            <el-table-column label="图片" width="100" align="center">
              <template slot-scope="scope">
                <el-upload
                  :action="CMBASE.baseUploadAction"
                  :file-list="scope.row.fileList"
                  :show-file-list="false"
                  :on-preview="handlePreview"
                  :on-remove="(value,fileList)=> handRemoveColumn(scope.$index, value,fileList)"
                  :on-success="(value)=> handleAvatarSuccessColumn(scope.$index,value)"
                  class="upload-demo  avatar-uploader "
                  list-type="picture"
                  disabled
                >
                  <img v-if="scope.row.skuImgurl" :src="scope.row.skuImgurl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon" />
                </el-upload>
              </template>
            </el-table-column>
            <el-table-column label="库存" width="100" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.skuStock" oninput="value=value.replace(/[^\d]/g,'')" />
              </template>
            </el-table-column>
            <el-table-column label="重量(千克)" width="100" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.skuWeight" />
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>

// import waves from '@/directive/waves'
import { getMAttrKeyListByparams, getGoodsSkuInfo, saveStockInfo } from '@/api/modules/goodsInfo'

export default {
  name: 'GoodsAttrForm',
  components: {},
  directives: {
    focus: {
      // 根据focusState的状态改变是否聚焦focus
      update: function(el, value) {
        // 第二个参数传进来的是个json
        if (value) {
          el.focus()
        }
      }
    }},
  filters: {},
  props: {
    // 商品ID
    rowGoodsId: {
      type: String,
      required: true
    },
    // 商品分类ID
    rowClassifyId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      listLoading: true,
      spceForm: {},
      spceFormRules: {},
      selectProductAttr: [],
      attrValueList: [],
      columnCheck: [],
      skuList: [],
      resSkuList: [], // 商品已保存规格值 多规格
      resSingleSkuList: [], // 商品已保存规格值 单规格

      templateData: [], // 每一个sku规格的数据
      dynamicTags: [], // 每一个sku规格里面拟定的数据如：颜色里面的[红色，蓝色，黄色]这些
      templateNameList: [], // 这个是第四步步骤里的for循环的颜色的模板名称，如[颜色，尺寸，库存，价格]
      resTemplateNameList: [], // 后台已保存规格名称
      attrKeyList: [],
      currentSelect: -1, // 当前选中的select框的 index
      activeName: 'first'
    }
  },
  created() {
    this.initFormData()
  },
  methods: {
    // 初始化表单数据
    initFormData() {
      this.listLoading = true
      console.log(this.rowGoodsId + '=======' + this.rowClassifyId)
      const row = { id: this.rowGoodsId, classifyId: this.rowClassifyId }
      // 获取商品属性信息
      this.getAttrKeyListByGoodsId(row.classifyId, row.id) // 属性多选框渲染
      // 根据商品id获取SKU列表
      this.getSkuListByGoodsId(row.id)
    },
    // 根据商品id 获取销售属性列表
    async getAttrKeyListByGoodsId(classify, goodsId) {
      // 【API请求】----获取销售属性列表
      await getMAttrKeyListByparams({ classifyId: classify, goodsId: goodsId }).then(response => {
        // this.selectProductAttr = response.data
        this.attrKeyList = response.data
      })
    },
    // 根据商品id获取 SKU列表
    getSkuListByGoodsId(goodsId) {
      // 获取sku信息
      getGoodsSkuInfo({ goodsId: goodsId }).then(response => {
        console.log(response)
        const resDate = response.result
        if (resDate == null || resDate.length === 0) {
          this.listLoading = false
          this.setSkuList()
          return
        }
        // 判断是否为单规格商品
        if (resDate.length === 1 && resDate[0].attrInfo == null) {
          const item = resDate[0]
          // 列表图片信息
          if (item.skuImgurl == null || item.skuImgurl === '') {
            item.fileList = []
          } else {
            const photoArray = []
            item.skuImgurl.split('__').forEach(item => {
              if (item !== '') {
                photoArray.push({ url: item })
              }
            })
            item.fileList = photoArray
          }
          this.skuList.push(item)
          this.resSingleSkuList = this.skuList
          this.listLoading = false
          return
        }
        // 以下为多规格
        this.activeName = 'second'
        // key列表
        const attrInfoTemp = JSON.parse(resDate[0].attrInfo)
        attrInfoTemp.forEach(item => {
          this.templateNameList.push(item.name)
        })
        this.resTemplateNameList = this.templateNameList
        // value列表
        resDate.forEach(item => {
          const attrInfoArray = JSON.parse(item.attrInfo)
          item.attrInfo = attrInfoArray // 列表SKU信息
          // 列表图片信息
          if (item.skuImgurl == null || item.skuImgurl === '') {
            item.fileList = []
          } else {
            const photoArray = []
            item.skuImgurl.split('__').forEach(item => {
              if (item !== '') {
                photoArray.push({ url: item })
              }
            })
            item.fileList = photoArray
          }
        })
        this.skuList = resDate
        this.resSkuList = resDate
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
        this.$message({ message: '商品SKU列表获取失败', type: 'error' })
      })
    },
    // 销售属性列渲染
    getProductSkuSp(row, index) {
      const valueName = row.attrInfo[index].value
      return valueName
    },

    // 图片上传成功后回显
    handleAvatarSuccessColumn(index, res) {
      this.skuList[index].skuImgurl = res.path
    },

    // 上传之前校验
    handlePreview(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/psd' || file.type === 'image/pdd'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传图片只能是jpeg/png/psd/pdd/ 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    // 移除一张图片
    handRemoveColumn(index, res, fileList) {
      if (fileList.length > 0) {
        const fileListArray = []
        fileList.forEach(item => {
          const start = this.CMBASE.baseFileContext.length
          const end = item.url.length
          const photoUrl = item.url.substring(start, end)
          fileListArray.push(photoUrl)
        })
        this.skuList[index].skuImgurl = fileListArray.join('__')
      } else {
        this.skuList[index].skuImgurl = ''
      }
    },

    setSkuList() {
      console.log('修改sku')
      this.skuList = []
      this.templateNameList = []
      var tmp = Date.parse(new Date()).toString().substr(0, 10)
      var rand = Math.floor(Math.random() * 900) + 100
      // 渲染SKU列表
      this.skuList.push({
        skuPrice: '0',
        skuCostprice: '0',
        skuSaleprice: '0',
        skuStock: '0',
        skuImgurl: '',
        skuCode: tmp + '-' + rand
      })
    },

    // 保存sku库存表单
    async saveStockFrom() {
      if (this.skuList.length === 0) {
        this.$message({ message: '请填写库存信息', type: 'error' })
        return
      }
      const skuInfoArray = []
      this.skuList.forEach(item => {
        skuInfoArray.push({
          id: item.id,
          goodsId: this.rowGoodsId,
          attrInfo: item.attrInfo, // 属性json信息
          skuPrice: item.skuPrice,
          skuCostprice: item.skuCostprice,
          skuSaleprice: item.skuSaleprice,
          skuWeight: item.skuWeight,
          skuStock: item.skuStock,
          skuImgurl: item.skuImgurl,
          skuCode: item.skuCode
        })
      })
      const skuInfoArrayStr = JSON.stringify(skuInfoArray)
      const res = await saveStockInfo({ skuInfoArray: skuInfoArrayStr })
      console.log('res', res)
      if (res.code === 0) {
        this.$emit('stockformcallback') // 只能用小写
        this.$emit('stockformcallback') // 只能用小写
      }
    }
  }
}

</script>
<style scoped lang="scss">
  .stepThird{
    .addSpecificaType{
      margin-bottom: 10px;
    }
    .itemTag{
      margin-bottom: 20px;
      .outerBorder{
        width: 100%;
        border: 1px solid #eee;
        border-radius: 5px;
        padding: 10px;
        box-sizing: border-box;
        position: relative;
        .close{
          position: absolute;
          right: 0;
          top: 0;
          i{
            font-size: 20px;
            cursor: pointer;
          }
        }
        .inputMar{
          margin-bottom: 10px;
        }
      }
    }
  }
  .stepFour{
    width: 100%;
    margin: auto;
    &__name{
      width: 100%;
      box-sizing: border-box;
      border: 1px solid #eee;
      display: flex;
      align-items: center;
      .item{
        flex: 1;
        width: 120px;
        height: 50px;
        line-height: 50px;
        text-align: center;
        font-size: 14px;
        border-right: 1px solid #eee;
        padding: 0 10px;
        box-sizing: border-box;
      }
    }
    &__box{
      &__panel{
        width: 100%;
        box-sizing: border-box;
        border: 1px solid #eee;
        display: flex;
        align-items: center;
        .item{
          flex: 1;
          width: 120px;
          height: 50px;
          line-height: 50px;
          text-align: center;
          font-size: 14px;
          border-right: 1px solid #eee;
          padding: 0 10px;
          box-sizing: border-box;
        }
      }
    }
  }
  .rigEnd {
    display: flex;
    justify-content: flex-end;
    margin-top: 10px;
    /*.previousBtn{
      color: #333;
      margin-right: 20px;
    }*/
    .saveBtn{
      width: 100px;
      height: 36px;
    }
  }
</style>
<style scoped>
  [v-cloak] {
    display: none;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 78px;
    height: 78px;
    line-height: 78px;
    text-align: center;
  }
  .avatar {
    width: 78px;
    height: 78px;
    display: block;
  }

  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }

</style>
